//
//  ViewController.m
//  tableViewSections
//
//  Created by 小白 on 16/3/3.
//  Copyright © 2016年 小白. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>
@property (nonatomic,copy) NSDictionary *sortName;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,copy) NSArray *keyArr;
//搜索控制器
@property (nonatomic,strong) UISearchController *searchController;
//保存搜索结果的数组
@property (nonatomic,copy) NSMutableArray *filterNames;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //读取数据
    NSString *path = [[NSBundle mainBundle]pathForResource:@"sortednames" ofType:@"plist"];
    self.sortName = [NSDictionary dictionaryWithContentsOfFile:path];
    //新建UITableView
    UITableView *tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 22, 320, 545)];
    [self.view addSubview:tabView];
    self.tableView = tabView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //sortName是个字典 要取key并排序
    NSArray *arr = [[self.sortName allKeys] sortedArrayUsingSelector:@selector(compare:)];
    self.keyArr = arr;
    //注册单元格模板 找不到重复的单元格时 会新建
    //类型默认为default
    //可省略下面的话
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
//    }
    //创建搜索控制器
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //处理搜索
    self.searchController.searchResultsUpdater = self;
    //搜索时背景是否变灰
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //将搜索的控制器的搜索栏作为表头视图
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    
}

#pragma mark - tabeview datasource adn Delegate Method
//当前有一张表格
//判断搜索控制的激活状态
//self。searchController.active
//如果是激活，那就提供搜索结果数据
//否则提供原本所以数据

//有几段
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return 1;
    }
    else
    {
    return self.keyArr.count;
    }
}

//第几段有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
       if (self.searchController.active) {
        return self.filterNames.count;
    }
    else
    {
        NSArray *arr = self.sortName[self.keyArr[section]];
        return arr.count;
    }
    
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
//    }
    if (self.searchController.active) {
        cell.textLabel.text = self.filterNames[indexPath.row];
        return cell;
    }
    else{
    cell.textLabel.text = self.sortName[self.keyArr[indexPath.section]][indexPath.row];
    return cell;
    }
}
//段头段尾文字
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return nil;
    }
    else{
    return self.keyArr[section];
    }
}    // fixed font style. use custom view (UILabel) if you want something different
//- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
//    return [NSString stringWithFormat:@"EndOf%@",self.keyArr[section]];
//}
//右侧导航
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.searchController.active) {
        return nil;
    }
    else{
    return self.keyArr;
    }
}
#pragma Mark - 搜索控制器的事件处理
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchController.searchBar.text;
    //定义了一个谓词对象
    //1.简单方法 ， 不忽略大小写
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"self contains %@",searchString];
    //2.用block创建谓词，可忽略大小写
//    NSPredicate *pre = [NSPredicate predicateWithBlock:^BOOL(NSString *name, NSDictionary<NSString *,id> * _Nullable bindings) {
//        NSRange range = [name rangeOfString:searchString options:NSCaseInsensitiveSearch];
//        return range.location != NSNotFound;
//    }];
    //遍历所有字母
    for (NSString *key in self.keyArr)
    {
        //得到该数组开头的人名数组
        NSArray *names = self.sortName[key];
        //使用谓词对象过滤数组
        NSArray *tmp = [names filteredArrayUsingPredicate:pre];
        [self.filterNames addObjectsFromArray:tmp];
        
    }
    [self.tableView reloadData];
  

}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
